#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author  : hu_cl
# @Contact : 760730895@qq.com 
# @Date    : 2020/7/14 17:12
# @File    : data_file_backups.py
import os
import paramiko
import time


class BackupFile(object):
    def __init__(self, host, username, password, port):
        self.host = host
        self.port = port
        self.username = username
        self.password = password
        self.ssh_client = paramiko.SSHClient()
        self.ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh_client.connect(hostname=self.host, username=self.username, password=self.password, port=self.port)

    def tar_files(self, tar_ssh_client, tar_file, tar_paths):
        # 压缩服务器上的目标文件
        tar_file_name = '{}_{}'.format(tar_file, time.strftime('%Y%m%d', time.localtime()))
        tar_commands = ('cd {}'.format(tar_paths), 'tar -cvPf {}.tar {}'.format(tar_file_name, tar_paths))
        # cd /home/py_work_oracle, tar -cvf py_work_oracle_20200722.tar /home/py_work_oracle
        tar_stdin, tar_stdout, tar_stderr = tar_ssh_client.exec_command(' \n '.join(tar_commands))
        res, err = tar_stdout.read(), tar_stderr.read()
        if err:
            print('执行压缩%s文件有信息返回为%s' % (tar_file, err.decode()))
        else:
            print('压缩%s文件成功' % tar_file)
        return tar_file_name

    def download_file(self, dl_ssh_client, dl_paths, dl_local, dl_file_name):
        # 从 linux 下载文件到 Windows
        ftp_client = dl_ssh_client.open_sftp()
        print('正在下载%s.tar，请等待' % dl_file_name)
        if not os.path.exists(dl_local):
            os.makedirs(dl_local)
        try:
            ftp_client.get('{}/{}.tar'.format(dl_paths, dl_file_name), r'{}/{}.tar'.format(dl_local, dl_file_name))
        except Exception as ex:
            print('下载文件%s.tar失败，请检查，错误信息为%s' % (dl_file_name, ex))
        else:
            print('下载%s.tar 文件成功' % dl_file_name)
        ftp_client.close()

    def remove_file(self, rm_ssh_client, rm_paths, rm_file_name):
        # 删除服务器上 生成的压缩文件
        commands = ('cd {}'.format(rm_paths),
                    'rm -f {}/{}.tar'.format(rm_paths, rm_file_name))
        rm_stdin, rm_stdout, rm_stderr = rm_ssh_client.exec_command(' \n '.join(commands))
        res, err = rm_stdout.read(), rm_stderr.read()
        if err:
            print('删除压缩%s.tar文件失败,错误信息为%s' % (rm_file_name, err.decode()))
        else:
            print('删除压缩%s.tar文件成功' % rm_file_name)

# 从 Windows 上传到 Linux
# ftp_client = ssh_client.open_sftp()
# ftp_client.put(r'e:\path\1\all_20180803.tar', '{}/{}.tar'.format(paths, file_name))
# ftp_client.close()
